<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>文件下载器</title>
</head>
<body>
  <div id="li"></div>
  <script type="text/javascript">
    const encoder = new TextEncoder("utf-8")
    const decoder = new TextDecoder("utf-8");
    let result = "";
    const list = document.getElementById('li')
    const writableStream = new WritableStream(
      {
        write(chunk) {
          return new Promise((resolve, reject) => {
            const buffer = new ArrayBuffer(1);
            const view = new Uint8Array(buffer);
            view[0] = chunk;
            console.log('view--->', view)
            const decoded = decoder.decode(view, { stream: true });
            const listItem = document.createElement("li");
            listItem.textContent = `Chunk decoded: ${decoded}`;
            list.appendChild(listItem);
            result += decoded;
            resolve();
          });
        },
        close() {
          const listItem = document.createElement("li");
          listItem.textContent = `[MESSAGE RECEIVED] ${result}`;
          list.appendChild(listItem);
        },
        abort(err) {
          console.error("Sink error:", err);
        },
      }
    );
    const writeLoad = async () => {
      const writer = writableStream.getWriter();
      const chunks = encoder.encode('这是一段数据', { stream: true })
      console.log('chunks--->', chunks)
      for (const chunk of chunks) {
        // 待前一个数据写入完成后再写入
        await writer.ready
        await writer.write(chunk)
      }
      // 在关闭 writer 前先保证所有的数据已经被写入
      await writer.ready()
      await writer.close()
    }
    writeLoad()
  </script>
</body>
</html>